package NewTmas.Listeners;

import NewTmas.FramesandPanels.JobGraphPanel;
import taskmaster.job.Task;
import taskmaster.job.TaskCollection;
import taskmaster.job.TaskToChange;
import taskmaster.util.Global;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: jhauser
 * Date: Jun 16, 2011
 * Time: 10:59:18 AM
 * To change status of a task.A dialog box(JOptionPane) will popup for confirm.
 */
public class ChangeStatusActionListener implements ActionListener
{
    private int status_id;
    private TaskCollection taskCollection;

    private JobGraphPanel panel;
    Task concernedTask;
    String task, job;

    public ChangeStatusActionListener(JobGraphPanel panel, int status_id, TaskCollection taskCollection, String task)
    {

        this.panel = panel;
        this.status_id = status_id;
        this.taskCollection = taskCollection;
        this.task = task;
        this.job = panel.job;
    }

    public void actionPerformed(ActionEvent e1)
    {


        concernedTask = taskCollection.getTask(job, task);


        try
        {
            TaskToChange[] possibleChangeTasks = taskCollection.determineUpdatability(panel.user, job, task, String.valueOf(status_id), true, false, true);

            List<String> tobeCreatedCheckbox = new ArrayList<String>();
            for (TaskToChange refTask : possibleChangeTasks)
            {
                if (!refTask.hadBadLogic() && !refTask.hasSyncError())
                {
                    tobeCreatedCheckbox.add(refTask.task.getTaskTag());
                }

            }


            if (tobeCreatedCheckbox.size() == 1)
            {
                int input = JOptionPane.showConfirmDialog(null, "Do you want to commit the task " + task + " to " + Global.statusNames.get(status_id) + "?", "Commit changes ", JOptionPane.OK_CANCEL_OPTION);
                if (input == JOptionPane.OK_OPTION)
                {
                    taskCollection.changeTaskStatus(panel.user, task, job, status_id, "");
                    panel.task_status.get(task).changeStatusto(status_id);

                    panel.parentFrame.toRefresh();
                }

            } else
            {
                JPanel dialogPanel=new JPanel();
                JScrollPane scrollPane=new JScrollPane(dialogPanel);
                scrollPane.getViewport().add(dialogPanel );
                dialogPanel.setLayout(new BoxLayout(dialogPanel, BoxLayout.Y_AXIS));
                JLabel confirmQues =new JLabel( "Do you want to commit this task and its successors to "+ Global.statusNames.get(status_id)+" ?");
                dialogPanel.add(confirmQues);
                final JCheckBox[] taskCheckbox = new JCheckBox[tobeCreatedCheckbox.size()];
                int j = 0;
                for (String checkboxTag : tobeCreatedCheckbox)
                {
                    taskCheckbox[j] = new JCheckBox(checkboxTag);
                    if (checkboxTag.equalsIgnoreCase(task))
                    {
                        taskCheckbox[j].setSelected(true);
                    }
                    dialogPanel.add(taskCheckbox[j]);
                    j++;
                }

                final Object[] obj = new Object[taskCheckbox.length + 2];
                obj[0] = "Do you want to commit this task and its successors to "+ Global.statusNames.get(status_id)+" ?";
                for (int x = 1; x < obj.length-1; x++)
                {
                    obj[x] = taskCheckbox[x - 1];
                }

                final JCheckBox checkAll=new JCheckBox("Check all");
                obj[obj.length-1]=checkAll;
                dialogPanel.add(checkAll);
                checkAll.addItemListener(new ItemListener() {
                    public void itemStateChanged(ItemEvent e)
                    {
                        for(JCheckBox c:taskCheckbox)
                            c.setSelected(checkAll.isSelected());
                    }
                });

                scrollPane.setViewportView(dialogPanel);

                scrollPane.setPreferredSize(new Dimension(400,400))  ;

                Object message=scrollPane;

                int input_2 = JOptionPane.showConfirmDialog(null, message, "Commit changes ", JOptionPane.OK_CANCEL_OPTION);
                List<String> toChange = new ArrayList<String>();

                if (input_2 == JOptionPane.OK_OPTION)
                {
                    for (JCheckBox aTaskCheckbox : taskCheckbox)
                    {
                        if (aTaskCheckbox.isSelected())
                        {
                            toChange.add(aTaskCheckbox.getText());
                        }
                    }
                    String[] toChangeTasks = new String[toChange.size()];
                    toChange.toArray(toChangeTasks);

                    for (String taskName : toChangeTasks)
                    {
                        taskCollection.changeTaskStatus(panel.user, taskName, job, status_id, "");
                        panel.task_status.get(taskName).changeStatusto(status_id);

                    }
                    // need to refresh underlying panel and this job graph
                    panel.parentFrame.toRefresh();


                }
            }  //end of else


        } catch (Exception e)
        {
               JOptionPane.showMessageDialog(null, "Problem changing the status for the task : "+e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
           //TODO: cleanup after TaskCollection exception handling improved
            e.printStackTrace();
        }

    }     //end of actionperformed


}
